<?php abstract class RRD implements iExtensionsRequired, iReconfigurable {
	protected static $Socket  = NULL;
	protected static $ConnStr = '';
	protected static $LastOK  = NULL;
	public static function LastOK () {return (self::$LastOK);}
	public static function Reconfigure (array $Config) {
		$Host = (array_key_exists ('host', $Config)) ? $Config ['host'] : 'localhost';
		$Port = (array_key_exists ('port', $Config)) ? $Config ['port'] : 13900;
		$ConnStr = "$Host:$Port";
		if ((NULL !== self::$Socket) and ($ConnStr === self::$ConnStr)) {
			Out::I (Msg::NotReconnecting, $ConnStr);
			return (TRUE);
		}
		$Socket = @socket_create (AF_INET, SOCK_STREAM, SOL_TCP);
		if ($Socket === FALSE) {
			Out::W (Msg::SocketCreateFail, $ConnStr);
			$ErrCode = socket_last_error ();
			Out::W (Msg::ConnectionError, 'socket', $ErrCode, socket_strerror ($ErrCode));
			return (FALSE);
		}
		if (@socket_connect ($Socket, $Host, $Port)) {
			list (self::$Socket, self::$ConnStr) = array ($Socket, $ConnStr);
			Out::I (Msg::Connected, $ConnStr);
			return (TRUE);
		}
		Out::W (Msg::ConnectionFail, $ConnStr);
		$ErrCode = socket_last_error ();
		Out::W (Msg::ConnectionError, 'socket', $ErrCode, socket_strerror ($ErrCode));
		return (FALSE);
	}
	protected static function Send ($Buf) {
		if (NULL === self::$Socket) return (FALSE);
		$Left = strlen ($Buf);
		while ($Left) {
			$Sent = socket_write (self::$Socket, $Buf);
			$Left -= $Sent;
			$Buf = substr ($Buf, -$Left);
		}
		Out::D (Msg::RRDSent, $Buf);
	}
	protected static function Receive () {
		if (NULL === self::$Socket) return ('OK');
		$Result = socket_read (self::$Socket, 10240);
		Out::D (Msg::RRDReceived, $Result);
		return (trim ($Result));
	}
	public static function Exec ($Command, $Check = TRUE) {
		self::Send ($Command."\r\n");
		$Result = explode ("\n", self::Receive ());
		self::$LastOK = (0 === strpos (end ($Result), 'OK'));
		$Check and ! self::LastOK () and Out::W (Msg::RRDSent, $Command) and Out::W (Msg::RRDReceived, implode ("\n", $Result));
		return ($Result);
	}
	public static function __GetRequiredExtensions () {return ('sockets');}
} ?>